//
//  HomeViewController.swift
//  JMWB
//
//  Created by 个人电脑 on 16/3/13.
//  Copyright © 2016年 个人电脑. All rights reserved.
//

import UIKit
import SDWebImage
import MJRefresh

class HomeViewController: BaseViewController {

//    private lazy var titleBnt : UIButton = UIButton(type: .Custom)
    private lazy var titleBnt : titleButton = titleButton(type: .Custom)
    private lazy var popoverAnimator : PopoverAnimator = PopoverAnimator()
    private lazy var statusViewModels : [StatusViewModel] = [StatusViewModel]()
    private lazy var cellHeightCache : [String : CGFloat] = [String : CGFloat]()
    private lazy var tipLabel : UILabel = UILabel()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //判断用户是否登陆
        if !isLogin{
         visitorView.addRotationAnimate()
            return
        }
     setupNavigationBar()
     setupHeaderFooterView()

       setupTipLabel()
    
        
//        //将行高设为自适应高度
//       tableView.rowHeight = UITableViewAutomaticDimension
//        //估算高度
//       tableView.estimatedRowHeight = 200
    }
}
extension HomeViewController{

    private func setupNavigationBar(){
    
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendattention", target: self, action: "leftItemCilck")
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: "rightItemClick")
        
        titleBnt.setTitle("Amay首页展示", forState: .Normal)
        titleBnt.addTarget(self, action: "titleBtnCilck", forControlEvents: .TouchUpInside)
        navigationItem.titleView = titleBnt
  }
    private func setupHeaderFooterView(){
               //下拉刷新
        let headerView = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction: "loadNewData")
        headerView.setTitle("下拉刷新", forState: .Idle)
        headerView.setTitle("松开可以进行刷新", forState: .Pulling)
        headerView.setTitle("正在刷新中...", forState: .Refreshing)
        tableView.mj_header = headerView
        
        headerView.beginRefreshing()
        //上拉刷新

//        let footerView = MJRefreshAutoFooter(refreshingTarget: self, refreshingAction: "loadMoreData")
//        tableView.mj_footer = footerView
        
    }
    
    private func setupTipLabel(){
        // 1.将Label添加父控件
        navigationController?.navigationBar.insertSubview(tipLabel, atIndex: 0)
        // 2.设置frame
        tipLabel.frame = CGRect(x: 0, y: 12, width: UIScreen.mainScreen().bounds.width, height: 32)
        // 3.设置tipLabel的属性
        tipLabel.backgroundColor = UIColor.greenColor()
        tipLabel.textColor = UIColor.redColor()
        tipLabel.textAlignment = .Center
        tipLabel.font = UIFont.systemFontOfSize(14)
        tipLabel.hidden = true
    }

}
extension HomeViewController{
  
    @objc private func leftItemCilck(){
    print("leftItemCilck")
    }
    
    @objc private func rightItemClick(){
    print("rightItemClick")
    }

     @objc private func titleBtnCilck(){

        let popoverVc = PopoverViewController()
       //设置modal为自定义模式
        popoverVc.modalPresentationStyle = .Custom
        //设置转场代理
        popoverAnimator.presentedFrame = CGRect(x: 100, y: 55, width: 180, height: 250)
        //产生循环引用
//        popoverAnimator.animateCallBack = {(isPresented : Bool) -> () in
//            self.titleBnt.selected = isPresented
//        }
        popoverAnimator.animateCallBack = {[weak self] (isPresented : Bool) -> Void in
        self? .titleBnt.selected = isPresented
        
        }
        popoverVc.transitioningDelegate = popoverAnimator
        
        presentViewController(popoverVc, animated: true, completion: nil)
    }
}
extension HomeViewController{
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusViewModels.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //创建Cell
        let cell = tableView.dequeueReusableCellWithIdentifier("HomeCell") as! HomeViewCell
        
        //给cell设置数据
        cell.statusViewModel = statusViewModels[indexPath.row]
//   为避免上拉刷新时因网络太慢出现空白,所以使用这个方法可以更加加载新的数据 判断释放最后一个cell
        if indexPath.row == statusViewModels.count - 1 {
            loadMoreData()
        }
        return cell
    }
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        //取出模型数据
        let statusViewModel = statusViewModels[indexPath.row]
        //从缓存池中取出cell的高度
        var cellHeight :CGFloat? = cellHeightCache["\(statusViewModel.status!.id)"]
        //判断高度是否有值
        if cellHeight != nil{
        return cellHeight!
        }
        //取出indexPath对应的cell
        let cell = tableView.dequeueReusableCellWithIdentifier("HomeCell") as! HomeViewCell
        //获取cell的高度
        cellHeight = cell.cellHeight(statusViewModel)
        //缓存高度
        cellHeightCache["\(statusViewModel.status?.id)"] = cellHeight!
        
       return cellHeight!
    }
}

extension HomeViewController {
    /// 请求最新的数据
    @objc private func loadNewData() {
        loadStatuses(true)
    }
    
    @objc private func loadMoreData() {
        loadStatuses(false)
    }
    
    /// 请求首页数据
    private func loadStatuses(isNewData : Bool) {
        // 1.获取请求参数
        var since_id : Int = 0
        var max_id : Int = 0
        if isNewData {
            since_id = statusViewModels.first?.status?.id ?? 0
        } else {
            max_id = statusViewModels.last?.status?.id ?? 0
            max_id = max_id == 0 ? 0 : max_id - 1
        }
        
        // 2.请求数据
        NetworkTools.shareIntance.loadStatuses(since_id, max_id: max_id) { (result, error) -> () in
            // 1.错误校验
            if error != nil {
                print(error)
                self.tableView.mj_header.endRefreshing()
                return
            }
            
            // 2.判断数组是否有值
            guard let resultArray = result else {
                self.tableView.mj_header.endRefreshing()
                return
            }
            
            // 3.遍历数组,将数组中的字典转成模型对象
            var models = [StatusViewModel]()
            for resultDict in resultArray {
                let status = Status(dict: resultDict)
                let statusViewModel = StatusViewModel(status: status)
                models.append(statusViewModel)
            }
            
            if isNewData {
                self.statusViewModels = models + self.statusViewModels
            } else {
                self.statusViewModels += models
            }
            
            // 4.缓存图片
            self.cacheImages(models)
        }
    }
    
    /// 缓存图片
    private func cacheImages(models : [StatusViewModel]) {
        //0.创建group
        let group = dispatch_group_create()
        
        // 1.缓存图片
        // 1.1.遍历所有的微博
        for status in statusViewModels {
            // 1.2.遍历所有的微博中url
            for url in status.picURLs {
                
                // 1.3.将一部请求加载group中
                dispatch_group_enter(group)
                
                // 1.4.缓存图片
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (_, _, _, _, _) -> Void in
                    
                    // 1.5.将异步处理从group中移除掉
                    dispatch_group_leave(group)
                })
            }
        }
        
        // 2.刷新表格
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            // 1.刷新表格
            self.tableView.reloadData()
            
            // 2.停止刷新
            self.tableView.mj_header.endRefreshing()
//            self.tableView.mj_footer.endRefreshing()
            //3.显示提示的Label,并且执行动画
            self.showTipLabelAnim(models.count)
        }
    }
    
    private func showTipLabelAnim(count : Int){
        tipLabel.hidden = false
        tipLabel.text = count == 0 ? "没有新微博" : "\(count)条新微博"
        //执行动画
        UIView .animateWithDuration(1.0, animations: { () -> Void in
            self.tipLabel.frame.origin.y = 44
            }) { (_) -> Void in
                UIView .animateWithDuration(1.0, delay: 1.0, options: [], animations: { () -> Void in
                    self.tipLabel.frame.origin.y = 12
                    }, completion: { (_) -> Void in
                        self.tipLabel.hidden = true
                })
        }
    }
}
